;(function(w){
    "use strict";

    if (!w['embedear']) {
        return false;
    }

    var $ = w['embedear'];

    var apiBase = $.protocol + '://qiita.com/api/v2/items/',

    cache = new Object(),

    setData = function(element, json) {
        var tags = json.tags;
        var html = '';
        html += '<div class="-qiitaembed">';
        html += '<div class="-avatar"><img src="' + json.user.profile_image_url + '" width="40"></div>';
        html += '<div class="-title"><a href="' + json.url + '" target="_blank">' + json.title + '</a></div>';
        if (tags.length) {
            html += '<div class="-tags">';
            for (var i = 0, l = json.tags.length; i < l; i++) {
                html += '<span class="-tag">';
                html += '<img src="' + tags[i].icon_url + '" width="16">';
                html += '<i><span class="-fa -fa-tag"></span>' + tags[i].name + '</i>';
                html += '</span>';
            }
            html += '</div>';
        }
        html += '<div class="-meta">';
        html += '<div class="-user"><a href="http://qiita.com/' + json.user.id + '" target="_blank">' + json.user.name + '</a></div>';
        html += '<div class="-created">' + $.dateFormat(json.created_at) + '</div>';
        html += '</div>';
        html += '</div>';

        element.innerHTML = html;
        element.className = element.className + ' -loaded';
        element.style.display = 'block';
    },

    init = function() {
        var elements = $.getElements('.-qiita-card', function(i, element, last){
            var postId = element.getAttribute("data-id");
            if (!postId) {
                return false;
            }

            element.style.display = 'none';

            if (cache[postId]) {
                setData(element, cache[postId]);
            } else {
                $.getJson(apiBase + postId, function(res){
                    cache[postId] = res;
                    setData(element, res);
                });
            }
        });

        if (elements.length) {
            $.loadCss('qiita/style.css');
        }
    };
    

    if (w.addEventListener) {
        w.addEventListener('load', init, false);
    } else if (w.attachEvent) {
        w.attachEvent('onload', init);
    }
})(window);